package com.wanmait.teatrain.controller;

import com.wanmait.teatrain.entity.Admin;
import com.wanmait.teatrain.dto.LoginDTO;
import com.wanmait.teatrain.service.AdminService;
import com.wanmait.teatrain.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController {
    //过期时间
    @Value("${code.expireMinutes}")
    private int expireMinutes;
    //Redis
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    //随机
    private Random random = new Random();
    @Autowired
    private AdminService adminService;
    //生成验证码图片
    @GetMapping("code")
    public AjaxResult getCode() throws IOException {
        // 1. 创建缓存图片：指定宽
        int width = 90, height = 30;
        //参数：宽，高，图片模式
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 2. 获取画笔对象
        Graphics graphics = bufferedImage.getGraphics();
        // 3. 设置画笔颜色
        graphics.setColor(Color.WHITE);
        // 4. 填充矩形区域
        graphics.fillRect(0, 0, width, height);
        // 5. 从字符数组中随机得到字符
        char[] arr = {
                '0', '1', '2', '3', '4', '5', '6','7','8','9'};
        // 6. 循环4次，画4个字符
        String code="";
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(arr.length);
            char c = arr[index];  //随机得到一个字符
            code = code+c;
            // 7. 设置字的颜色为随机
            graphics.setColor(getRandomColor());
            // 8. 设置字体，大小为18。参数：字体，样式，大小
            graphics.setFont(new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 19));
            // 9. 将每个字符画到图片，x增加，y不变。
            //参数：画字符，x位置，y位置。把c从字符转成字符串
            graphics.drawString(String.valueOf(c), 10 + (i * 20), 20);
        }

        //干扰线
        for (int i = 0; i < 10; i++) {
            // 10. 线的位置是随机的，x范围在width之中，y的范围在height之中。
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            // 11. 画8条干扰线，每条线的颜色不同
            graphics.setColor(getRandomColor());
            graphics.drawLine(x1, y1, x2, y2);
        }
        //ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", baos);
        byte[] bytes = baos.toByteArray();

        Base64.Encoder encoder = Base64.getEncoder();
        //base64字符串
        String base64 = encoder.encodeToString(bytes).trim();
        base64 = base64.replaceAll("\n", "").replaceAll("\r","");
        //为了以后校验验证法是否正确，需要把code保存到redis中
        //唯一键
        String codeKey = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("code:"+codeKey,code,expireMinutes, TimeUnit.MINUTES);

        return AjaxResult.success().put("codeImg",base64).put("codeKey",codeKey);

    }

    /**
     写一个方法随机获取颜色
     */
    private Color getRandomColor() {
        //随机生成0-255之间整数
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        //参数：红，绿，蓝 (0-255)
        return new Color(red, green, blue);
    }

    //登陆方法
    @PostMapping("login")
    public AjaxResult login(@Validated @RequestBody LoginDTO loginDTO, HttpServletRequest servletRequest){
        //获取远程登录ip地址
        String ip = servletRequest.getRemoteAddr();
        Admin admin = new Admin();
        admin.setUsername(loginDTO.getUsername()).setPassword(loginDTO.getPassword()).setLoginIp(ip).setLoginTime(new Date());
        //传入ip 用户对象 code
        return adminService.login(admin,loginDTO.getCode(),loginDTO.getCodeKey());
    }
}
